package com.e2a.examenenligne.mangedbeanService;



import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@ManagedBean(name="loginBean")
@SessionScoped
public class LoginBean {
	
	private String username;

	private String password;


	public LoginBean() {
		  
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(false);

		if (session != null) {

			session.invalidate();
		}

	}

	public String getUsername() {

		return username;

	}

	public void setUsername(String username) {

		this.username = username;

	}

	public String getPassword() {

		return password;

	}

	public void setPassword(String password) {

		this.password = password;

	}

	public String login() {

		// on recupère context de la servlet 
        FacesContext context = FacesContext.getCurrentInstance();
//on perend request
        HttpServletRequest request = (HttpServletRequest) 
context.getExternalContext().getRequest();
        try {
            String navigateString = "";
           
 // Checks if username and password are
            request.login(username, password);
            // gets the user principle and navigates to the appropriate page
           
            if (request.isUserInRole("Admin")) {
                navigateString = "/Administrateur/index.xhtml";
                return "success";
            } else if (request.isUserInRole("Expert")) {
                navigateString = "/Expert/index.xhtml";
                return "success2";
            } else if (request.isUserInRole("Client")) {
                navigateString = "/Utilisateur/index.xhtml";
                return "success3";
            } 

			//FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,navigateString, null));

			return "failure";

		} catch (ServletException e) {

			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"An Error Occured: Login failed", null));

			e.printStackTrace();
			
			 return "failure";
		}


	}

	public void logout() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(false);

		if (session != null) {

			session.invalidate();

		}

		FacesContext
				.getCurrentInstance()
				.getApplication()
				.getNavigationHandler()
				.handleNavigation(FacesContext.getCurrentInstance(), null,"/acceuil.xhtml");

	}

}
